package main.java.com.lee.pattern.asynccallback.jdk;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 喝茶
 * 使用CompletableFuture实现喝茶案例,
 * 线程1, 负责烧水, 线程2负责, 洗茶杯, 主线程调度1,2 然后泡茶
 *
 * @author winston
 * @date 2022/02/21
 */
public class DrinkTea {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        supplierVersion();
    }


    public static void sleep(Integer second) {
        try {
            Thread.sleep(second * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void runVersion() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> water = CompletableFuture.runAsync(() -> {
            System.out.println("开始烧水");
            sleep(1);
        });

        CompletableFuture<Void> wash = CompletableFuture.runAsync(() -> {
            System.out.println("洗茶杯");
            sleep(2);
        });

        CompletableFuture<Void> future = CompletableFuture.allOf(wash, water).thenRun(() -> {
            System.out.println("准备工作完成");
        });

        future.get();
    }

    public static void supplierVersion() {
        CompletableFuture<Boolean> water = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始烧水");
            sleep(1);
            return true;
        });

        CompletableFuture<Boolean> wash = CompletableFuture.supplyAsync(() -> {
            System.out.println("洗茶杯");
            sleep(2);
            return true;
        });

        CompletableFuture<Object> combine = wash.thenCombine(water, (a, b) -> {
            if (a && b) {
                System.out.println("准备工作完成");
            }
            return null;
        });


        combine.join();
    }
}
